package com.hello.file.service;

import java.io.InputStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import com.alibaba.nacos.common.utils.IoUtils;
import com.hello.file.config.MinioConfig;
import com.hello.file.utils.FileLogUtils;
import com.hello.file.utils.FileUploadUtils;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;

/**
 * Minio 文件存储
 *
 * @author hello
 */
@Service
public class MinioSysFileServiceImpl implements ISysFileService
{
    private static final Logger log = LoggerFactory.getLogger(MinioSysFileServiceImpl.class);

    @Autowired
    private MinioConfig minioConfig;

    @Autowired
    private MinioClient client;

    @Value("${minio.endpoint:}")
    private String endpoint;
    
    @Value("${minio.bucketName:}")
    private String bucketName;

    /**
     * Minio文件上传接口
     *
     * @param file 上传的文件
     * @return 访问地址
     * @throws Exception
     */
    @Override
    public String uploadFile(MultipartFile file) throws Exception
    {
        // 使用文件日志工具记录开始上传
        FileLogUtils.logFileUploadStart("Minio对象存储", file, bucketName);
                
        String fileName = FileUploadUtils.extractFilename(file);
        InputStream inputStream = file.getInputStream();
        PutObjectArgs args = PutObjectArgs.builder()
                .bucket(bucketName)
                .object(fileName)
                .stream(inputStream, file.getSize(), -1)
                .contentType(file.getContentType())
                .build();
                
        log.info("准备上传文件到Minio，ContentType: {}", file.getContentType());
        
        try {
            client.putObject(args);
            IoUtils.closeQuietly(inputStream);
            
            String url = endpoint + "/" + bucketName + "/" + fileName;
            
            // 使用文件日志工具记录上传成功
            FileLogUtils.logFileUploadSuccess("Minio对象存储", fileName, url);
            
            return url;
        } catch (Exception e) {
            // 使用文件日志工具记录上传失败
            FileLogUtils.logFileUploadError("Minio对象存储", fileName, e.getMessage());
            throw e;
        }
    }
}
